import { defineStore } from "pinia";
import { ref } from 'vue'
import request from '@/utils/request'
import { ElMessage } from "element-plus";
export const useRoleStore = defineStore('RoleStore', () => {
    const roleSearch = ref({ name: '' })
    const pageInfo = ref({ current: 1, pageSize: 5, total: 0 })
    const roles = ref([])
    const ids = ref([])
    const updateDialogVisible = ref(false)
    const roleFrom = ref({})
    const menuDialogVisible = ref(false)
    const menuRef = ref([])
    const defaultCheckedKeys = ref([])
    const checkedKeys = ref({ id: 0, keys: [] })
    const menuData = ref([
        {
            id: 1,
            label: '主页',
        },
        {
            id: 2,
            label: '系统管理',
            children: [
                {
                    id: 4,
                    label: '用户管理',
                },
                {
                    id: 5,
                    label: '文件管理',
                },
                {
                    id: 6,
                    label: '权限管理',
                },
                {
                    id: 7,
                    label: '菜单管理',
                },
                {
                    id: 8,
                    label: '文件管理',
                },
            ],
        },
        {
            id: 3,
            label: '系统设置',
        },
    ])
    const getRoles = async () => {
        const { data: { total, records } } = await request.get('/role/page', {
            params: {
                current: pageInfo.value.current,
                pageSize: pageInfo.value.pageSize,
                name: roleSearch.value.name
            }
        })
        roles.value = records
        pageInfo.value.total = total
    }
    const getMenus = async () => {
        // 获取所有菜单
        const { data } = await request.get('/menu', {
            params: {
                name: ''
            }
        })
        // 获取对应的权限对应的菜单
        menuData.value = extractProperties(data)
    }
    const getCheckedMenu = async (roleId) => {
        defaultCheckedKeys.value = []
        menuDialogVisible.value = true
        getMenus()
        const { data } = await request.get(`/role/roleId/${roleId}`)
        defaultCheckedKeys.value = data
        checkedKeys.value.id = roleId
    }
    const save = async () => {
        const result = await request.post('/role', roleFrom.value)
        if (result.code === 200) {
            ElMessage.success('保存成功')
            updateDialogVisible.value = false
            getRoles()
        } else {
            ElMessage.warning(result.msg)
        }
    }
    const refresh = () => {
        roleSearch.value = { name: '' }
        getRoles()
    }
    const deleteRole = async (id) => {
        const result = await request.delete(`/role/${id}`)
        result.code === 200 ? ElMessage.success('保存成功') : ElMessage.warning(result.msg)
        getRoles()
    }
    const deleteRoles = async () => {
        const result = await request.delete('/role', {
            data: ids.value
        })
        result.code && result.code === 200 ? ElMessage.success('删除成功') : ElMessage.warning(result.msg)
        getRoles()
    }
    const handleSelectionChange = (val) => {
        ids.value = val.map(item => item.id)
    }
    const EditRole = (row) => {
        roleFrom.value = row
        updateDialogVisible.value = true
    }
    const addCheckedKeys = async () => {
        checkedKeys.value.keys = menuRef.value.getCheckedKeys(true)
        const result = await request.post(`/role/menu`, checkedKeys.value)
        if (result.code === 200) {
            ElMessage.success('绑定成功')
        } else {
            ElMessage.success(result.msg)
        }
        menuDialogVisible.value = false;
    }

    // 处理tree对象数组工具
    function extractProperties(data) {
        if (!Array.isArray(data)) {
            return null;
        }

        return data.map(item => {
            const extractedNode = {
                id: item.id,
                label: item.name,
            };

            if (item.children) {
                extractedNode.children = extractProperties(item.children);
            }

            return extractedNode;
        });
    }

    return {
        roles,
        roleSearch,
        pageInfo,
        updateDialogVisible,
        roleFrom,
        menuDialogVisible,
        menuData,
        menuRef,
        defaultCheckedKeys,
        getRoles,
        save,
        deleteRole,
        refresh,
        deleteRoles,
        EditRole,
        handleSelectionChange,
        // handleCheckChange,
        addCheckedKeys,
        getCheckedMenu
    }
})